﻿package com.zhonglian.nourish.view.d.activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LevelListDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.zhonglian.nourish.R;
import com.zhonglian.nourish.base.BaseActivity;
import com.zhonglian.nourish.utils.LogUtil;
import com.zhonglian.nourish.utils.StatusBarUtil;
import com.zhonglian.nourish.utils.ToastUtils;
import com.zhonglian.nourish.utils.dialogs.DialogLoadingUtil;
import com.zhonglian.nourish.view.d.presenter.DPresenter;
import com.zhonglian.nourish.view.login.viewer.IPublicViewer;

import java.lang.ref.WeakReference;
import java.net.URL;

/**
 * Created : Yx
 * Time : 2019/11/15 16:37
 * Describe :关于我们
 */
public class AboutUsActivity extends BaseActivity implements IPublicViewer {
    private TextView tvLeft, tvTitle;

    private TextView about_us_msg;

    private LevelListDrawable mDrawable = new LevelListDrawable();
    private MyHandler handler;
    public final static String HTML_TEXT =
            "<p><font size=\"3\" color=\"red\">设置了字号和颜色</font></p> \n" +
                    "<b><font size=\"5\" color=\"blue\">设置字体加粗 蓝色 5号</font></b></br>\n" +
                    "<h1>这个是H1标签</h1></br>\n" +
                    "<p>这里显示图片：</p>\n" +
                    "<img src=\"https://img0.pconline.com.cn/pconline/1808/06/11566885_13b_thumb.jpg\"/>";

    @Override
    public int initLayout() {
        return R.layout.activity_about_us;
    }

    @Override
    public void initView() {
        StatusBarUtil.setStatusTextColor(true, this);
        tvLeft = findViewById(R.id.tv_left);
        tvTitle = findViewById(R.id.tv_title);
        tvTitle.setText("关于我们");
        tvLeft.setOnClickListener(clicks);

        about_us_msg = findViewById(R.id.about_us_msg);

        handler = new MyHandler(this);

        DialogLoadingUtil.showLoading(this);
        DPresenter.getInstance().getAboutus(this);


    }

    private View.OnClickListener clicks = v -> {
        switch (v.getId()) {
            case R.id.tv_left:
                finish();
                break;
        }
    };

    @Override
    public void onSuccess(String str) {
        DialogLoadingUtil.hidn();
        Spanned result;
        if (!TextUtils.isEmpty(str)) {
            //设置富文本数据
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                result = Html.fromHtml(str, Html.FROM_HTML_MODE_LEGACY, imageGetter, null);
            } else {
                result = Html.fromHtml(str, imageGetter, null);
            }
            about_us_msg.setText(result);
        } else {
            about_us_msg.setText("暂无");//简介
        }
    }

    @Override
    public void onFail(String str) {
        DialogLoadingUtil.hidn();
        ToastUtils.showToastApplication(str);
    }


    Html.ImageGetter imageGetter = new Html.ImageGetter() {
        @Override
        public Drawable getDrawable(String source) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    mDrawable.addLevel(0, 0, ContextCompat.getDrawable(AboutUsActivity.this, R.mipmap.ic_launcher));
                    mDrawable.setBounds(0, 0, 200, 200);

                    Bitmap bitmap;
                    try {
                        bitmap = BitmapFactory.decodeStream(new URL(source).openStream());
                        Message msg = handler.obtainMessage();
                        msg.what = 1206;
                        msg.obj = bitmap;
                        handler.sendMessage(msg);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }).start();

            return mDrawable;
        }
    };

    /**
     * 避免handler内存泄露的写法
     * handler为何会导致内存泄露：
     * 如果handler为内部类（非静态内部类），那么会持有外部类的实例，
     * 若在handler.sendMessage的时候，activity finish掉了，那么此时activity将无法得到释放
     * <p>
     * 如果申明handler为静态内部类，则不会含有外部类的引用，
     * 但是需要在handler中更新UI（注意此时handler为static），则需要引入一个activity引用，
     * 显然必须是弱引用，否则会导致和上面一样的结果
     * <p>
     * 使用activity弱引用
     * 之所以使用弱引用，是因为handler为static,使用activity的弱引用来访问activity对象内的成员
     */
    private static class MyHandler extends Handler {
        private WeakReference<AboutUsActivity> weakReference;
//        private HandlerOOMActivity activity;

        public MyHandler(AboutUsActivity activity) {
            weakReference = new WeakReference<>(activity);
//            this.activity = activity;
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            LogUtil.iYx("handleMessage: ");
//            HandlerOOMActivity activity = weakReference.get();
            switch (msg.what) {
                case 1206:
                    Bitmap bitmap = (Bitmap) msg.obj;
                    BitmapDrawable drawable = new BitmapDrawable(null, bitmap);

                    AboutUsActivity activity = weakReference.get();
                    if (activity != null) {
                        activity.mDrawable.addLevel(1, 1, drawable);
                        activity.mDrawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
                        activity.mDrawable.setLevel(1);

                        CharSequence charSequence = activity.about_us_msg.getText();
                        activity.about_us_msg.setText(charSequence);
                        activity.about_us_msg.invalidate();
                    }
                    break;
            }
        }
    }


}
